package com.book.configure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * Description： 限流配置
 *
 * @Author： leo.xiong
 * @CreateDate： 2019/10/15 20:46
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@Configuration
public class RateLimiterConfig {
    /**
     * IP限流，即以每秒内请求数按IP分组统计，超出限流的url请求都将返回429状态
     *
     * @return
     */
    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

    /**
     * 按URL限流,即以每秒内请求数按URL分组统计，超出限流的url请求都将返回429状态
     *
     * @return
     */
    @Bean
    public KeyResolver urlKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }

    /**
     * 按某字段(user)限流，即以每秒内请求数按user分组统计，超出限流的url请求都将返回429状态
     *
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }
}
